import { fromJS } from 'immutable';
import React, { Component } from 'react';
import { StoreProvider } from 'iflux2';
import AppStore from './store';
import { Button, Switch, message, Tabs } from 'antd';
const TabPane = Tabs.TabPane;
import GaUtil from 'util/ga-util';
import WebApi from './webapi';

import MassInput from 'uikit/mass-input';
import FilterItem from './component/filter-item';
const MAX_USERS = 10000;
@StoreProvider(AppStore)
export default class Mass extends Component {
	static defaultProps = {
	};
  constructor(props) {
    super(props);
    this.state = {
      disabled: false,
      params: {
        send_ignore_reprint: 0,
        message: {
          msgtype: 'text',
          text: {
            content: ''
          }
        }
      }
    };
  }

  componentDidMount() {
    this.props.store.fetchFansCount();
  }

  render() {
    let { send_ignore_reprint } = this.state.params;
    let { conditionList = [],totalCount } = this.props.store.state().toJS();
    let co = conditionList.length
      ? conditionList.map((item, index) => {
          return <FilterItem {...item} index={index} />;
        })
      : null;
    return (
      <div className="mass">
        <Tabs type="card">
          <TabPane tab="群发消息" key="all">
            <div className="mass-reprint">
              <span>是否群发被判定为转载内容</span>
              <Switch defaultChecked={!!send_ignore_reprint} onChange={this._check} />
            </div>
            <div className="mass-reprint">
              <span>根据以下条件筛选:</span>
            </div>
            {co}
            <div className="mass-reprint" style={{ display: 'block' }}>
              <span>{`接收人数：${totalCount}`}</span>
            </div>
            <MassInput ref="MassInput" textMaxLength={600} onChange={this._change} tabs={['text', 'mpnews', 'image']} />
            <div className="mass-btns">
              <Button type="primary" disabled={this.state.disabled} onClick={this._mass}>立即群发</Button>
            </div>
          </TabPane>
        </Tabs>
      </div>
    );
  }

  _check = checked => {
    this.state.params.send_ignore_reprint = checked ? 1 : 0;
    if (!checked) {
      GaUtil.addEvent({ eventAction: '非原创取消群发', eventLabel: '群发消息' });
    }
    this.setState(this.state);
  };

  _change = ({ type, data }) => {
    this.state.params.message = {
      msgtype: type,
      [type]: {
        text: {
          content: data
        },
        mpvideo: {
          media_id: data && data.media_id,
          title: '',
          description: ''
        },
        other: {
          media_id: data && data.media_id
        }
      }[
        {
          text: 'text',
          mpvideo: 'mpvideo'
        }[type] || 'other'
      ]
    };
    this.setState(this.state);
  };

  _mass = async () => {
    let { params } = this.state,
      type = params.message.msgtype,
      data = params.message[type];
	  await this.props.store.fetchFans();
    let { touser } = this.props.store.state().toJS();
    if (touser.length < 2) {
      message.warning('微信群发的人数必须大于1人');
      return;
    }
    if (data && (data.content || data.media_id)) {
      if (type === 'news') {
        console.log('高级图文');
      } else {
        this.setState({ disabled: true });
	
	      try {
		      let len = touser.length;
		      if (len > MAX_USERS) {
			      //多次发送
			      for (let start = 0, length = touser.length; start < length; start += MAX_USERS) {
				      let end = start + MAX_USERS;
				      let _touser = touser.slice(start, end);
				      Object.assign(params, {touser: _touser});
				      await WebApi.send(params);
			      }
		      } else {
			      Object.assign(params, {touser});
			      await WebApi.send(params);
		      }
	      } catch (e) {
		      this.setState({ disabled: false });
	        throw e;
	      }
	      message.success('发送成功!');
        let _params = this.state.params;
        _params = fromJS(_params)
          .set('message', {
            msgtype: 'text',
            text: {
              content: ''
            }
          })
          .toJS();
        this.setState({ disabled: false, params: _params });
        this.refs.MassInput.init(false);
        GaUtil.addEvent({ eventAction: '群发', eventLabel: '群发消息', eventValue: type });
      }
    } else {
      message.warning(`请${type === 'text' ? '输入' : '选择'}内容`);
    }
  };
}

class MassCheckBox extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: !!this.props.value
    };
  }

  render() {
    let { checked } = this.state;

    return (
      <div className={`mass-switch${checked ? ' checked' : ''}`} onClick={this._change}>
        <div className="mass-switch-slider" />
      </div>
    );
  }

  _change = () => {
    let checked = !this.state.checked,
      { onChange } = this.props;
    this.setState({ checked });
    onChange && onChange(checked);
  };
}
